package com.proton.carepatchtemp.login.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.base.BaseFragment;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.oss.OSSUtils;
import com.yalantis.ucrop.UCrop;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class Guide2Fragment extends BaseFragment {

    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected Uri tempUri;
    private ImageView mAdd_avator;
    private View rootView;
    private String ossAvatorUri = "";
    private ProgressDialog mProgressDialog;
    protected Uri cropUri = Uri.fromFile(new File(FileUtils.avatar));

    public static Guide2Fragment newInstance() {
        Guide2Fragment f = new Guide2Fragment();
        Bundle args = new Bundle();
        f.setArguments(args);
        return f;
    }

    @Override
    public void dealEvent(MainEvent event) {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProgressDialog = new ProgressDialog(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_guide2, null);
        }
        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。 
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        bindViews(rootView);
        onClicks();
        return rootView;
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    private void bindViews(View rootView) {
        mAdd_avator = rootView.findViewById(R.id.add_avator);
//        mAdd_avator_default= (ImageView) rootView.findViewById(R.deviceId.add_avator_default);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void onClicks() {
        mAdd_avator.setOnClickListener(view -> findIamgeUrl());
    }

    public void findIamgeUrl() {
        showChoosePicDialog();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PICTURE:
                startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                break;
            case CHOOSE_PICTURE:
                startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                break;
            case UCrop.REQUEST_CROP:
                uploadPic();
                break;
        }
    }

    /**
     * 显示修改头像的对话框
     */
    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getString(R.string.string_set_avatar));
        String[] items = {getString(R.string.string_select_photo), getString(R.string.string_take_photo)};
        builder.setNegativeButton(getString(R.string.string_cancel), null);
        builder.setItems(items, (dialog, which) -> {
            switch (which) {
                case CHOOSE_PICTURE: // 选择本地照片
                    openGallery();
                    break;
                case TAKE_PICTURE: // 拍照
                    openCamera();
                    break;
            }
        });
        builder.create().show();
    }

    private void openGallery() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
    }

    private void openCamera() {
        try {
            File file = new File(FileUtils.getDataCache(), "image.jpg");
            Intent openCameraIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                tempUri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".FileProvider", file);//通过FileProvider创建一个content类型的Uri
            } else {
                tempUri = Uri.fromFile(file);
            }
            // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
            startActivityForResult(openCameraIntent, TAKE_PICTURE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 裁剪图片方法实现
     */
    protected void startPhotoZoom(Uri uri) {
        UCrop.of(uri, cropUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(300, 300)
                .start(getActivity());
    }

    private void uploadPic() {
        // 拿着imagePath上传了
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                mProgressDialog.setMessage(getString(R.string.string_uploading));
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                ossAvatorUri = OSSUtils.uploadImg(FileUtils.avatar);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                mAdd_avator.setVisibility(View.VISIBLE);
                mAdd_avator.setImageURI(Uri.parse(ossAvatorUri));
                mProgressDialog.dismiss();
                EventBus.getDefault().post(new MainEvent(Codes.POST_AVATOR, ossAvatorUri));
                super.onPostExecute(aVoid);
            }
        }.execute();
    }

}
